package com.sxkf.core.third.im.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.jeecg.common.exception.SxkfException;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Map;

public class HttpUtil {
    private static final OkHttpClient client = new OkHttpClient();

    public static JSONObject post(String url, Map<String, String> headers, String requestBody) {
        // 构建请求体
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody);

        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);

        // 添加请求头
        return call(headers, requestBuilder);
    }

    public static JSONObject patch(String url, Map<String, String> headers, String requestBody) {
        // 构建请求体
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody);

        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .patch(body);

        // 添加请求头
        return call(headers, requestBuilder);
    }

    public static JSONObject delete(String url, Map<String, String> headers) {
        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .delete();

        // 添加请求头
        return call(headers, requestBuilder);
    }

    public static JSONObject delete(String url, Map<String, String> headers, String requestBody) {
        // 构建请求体
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody);

        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .delete(body);

        // 添加请求头
        return call(headers, requestBuilder);
    }

    public static JSONObject get(String url, Map<String, String> headers) {
        // 构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .get();

        // 添加请求头
        return call(headers, requestBuilder);
    }

    @Nullable
    private static JSONObject call(Map<String, String> headers, Request.Builder requestBuilder) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            requestBuilder.addHeader(entry.getKey(), entry.getValue());
        }

        Request request = requestBuilder.build();

        // 执行请求
        try (Response response = client.newCall(request).execute()) {
            if (response.body() == null || !response.isSuccessful()) {
                throw new SxkfException("Unexpected code " + response);
            }
            return JSON.parseObject(response.body().string());
        } catch (IOException e) {
            throw new SxkfException(e.getMessage());
        }
    }

}
